#ifndef SERVER_FUNCTIONS_H
#define SERVER_FUNCTIONS_H

#define _GNU_SOURCE  // 启用GNU扩展，包括strdup函数

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <pthread.h>
#include <sys/time.h>  // 用于struct timeval和settimeofday
#include <time.h>      // 用于时间函数

// 定义Windows到Linux的类型映射
typedef int SOCKET;
#define INVALID_SOCKET (-1)
#define SOCKET_ERROR (-1)

#define BUFFER_SIZE 4096
#define SERVER_PORT 8080
#define SERVER_VERSION "1.0"
#define MAX_UPLOAD_SIZE (50 * 1024 * 1024)  // 50MB最大上传文件大小
#define UPLOAD_DIR "./uploads"  // 上传文件存储目录

// 定义CGI参数结构体
typedef struct {
    char *name;
    char *value;
} Param;

// 定义文件上传信息结构体
typedef struct {
    char *filename;
    char *content_type;
    char *data;
    size_t data_size;
} UploadFile;

// 定义配置结构体
typedef struct {
    int port;
    char *document_root;
    int max_connections;
} Config;

extern Config config;

// 工具函数声明
void parse_http_request(char *request, char **method, char **path, char **query);
void handle_get_request(SOCKET client_socket, char *path, char *query);
void handle_post_request(SOCKET client_socket, char *path, char *content);
void send_json_response(SOCKET client_socket, const char *json, int status_code);
void send_file(SOCKET client_socket, const char *file_path);
void list_directory(SOCKET client_socket, const char *dir_path);
char *get_file_content(const char *file_path);
char *get_mime_type(const char *file_path);
Param *parse_query_string(char *query, int *param_count);
void free_params(Param *params, int param_count);
void handle_cgi(SOCKET client_socket, const char *path, Param *params, int param_count);
void format_bytes(unsigned long long bytes, char *buffer, size_t buffer_size);
int get_tf_card_info(const char *mount_path, unsigned long long *total_bytes, 
                     unsigned long long *free_bytes, unsigned long long *used_bytes, 
                     double *usage_percent);

// 文件上传相关函数声明
int create_upload_directory(void);
int parse_multipart_data(const char *content, const char *boundary, UploadFile *upload_file);
int save_uploaded_file(const UploadFile *upload_file, const char *save_path);
void free_upload_file(UploadFile *upload_file);
char *extract_boundary(const char *content_type);
void handle_file_upload(SOCKET client_socket, const char *content, const char *content_type);
char *url_decode(const char *str);
int validate_filename(const char *filename);

#endif // SERVER_FUNCTIONS_H